package com.sc.nft.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sc.nft.dao.EcologyHatchCollecionShareProfitConfDao;
import com.sc.nft.dao.EcologyHatchDaoIncomeConfDao;
import com.sc.nft.dao.EcologyHatchShareProfitDao;
import com.sc.nft.dao.MarketManagementDaoPoolDao;
import com.sc.nft.dto.*;
import com.sc.nft.entity.*;
import com.sc.nft.enums.EcologyHatchShareProfitTypeEnum;
import com.sc.nft.enums.EcologyIncomeTypeEnum;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.service.*;
import com.sc.nft.util.WeChatUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 生态-结算-任务
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class EcologyHatchTask {

    private final UserEcologyHatchIncomeService userEcologyHatchIncomeService;
    private final EcologyHatchDaoIncomeConfDao ecologyHatchDaoIncomeConfDao;
    private final EcologyHatchShareProfitDao ecologyHatchShareProfitDao;
    private final EcologyHatchIncomeConfDao ecologyHatchIncomeConfDao;
    private final EcologyHatchConfDao ecologyHatchConfDao;
    private final EcologyHatchCollecionShareProfitConfDao ecologyHatchCollecionShareProfitConfDao;
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;
    private final EcologySmeltingService ecologySmeltingService;
    private final EcologyReforgeConfService ecologyReforgeConfService;
    private final AdminEcologyIncomeConfService adminEcologyIncomeConfService;
    private final MarketManagementDaoPoolDao marketManagementDaoPoolDao;
    private final Redisson redisson;
    private final EcologyHatchExchangeConfService ecologyHatchExchangeConfService;
    private final UserConsensusService userConsensusService;

    /**
     * 熔炼周期结算
     * @throws Exception
     */
    @XxlJob("settleHatch")
    public void settleHatch() throws Exception {
        userEcologyHatchIncomeService.settleHatch();
    }

    /**
     * 生态节点持仓奖
     */
    @XxlJob("ecologyNodeTakePositionIncome")
    public void ecologyNodeTakePositionIncome() throws Exception {
        userEcologyHatchIncomeService.ecologyNodeTakePsitionIncome();
    }


    /**
     * 生态培育奖  城主和生态节点
     * 1: 7天内(不包含当天的前7天)
     * 2: 365天内(不包含当天的前365天)
     * @throws Exception
     */
    @XxlJob("ecologyCultivateIncome")
    public void ecologyCultivateIncome() throws Exception {
        userEcologyHatchIncomeService.ecologyCultivateIncome();
    }

    /**
     * 生态贡献奖 城主和生态节点
     * 统计维度 :
     * 1: 7天内(不包含当天的前7天)
     * 2: 365天内(不包含当天的前365天)
     * @throws Exception
     */
    @XxlJob("ecologyContributionIncome")
    public void ecologyContributionIncome() throws Exception {
        userEcologyHatchIncomeService.ecologyContributionIncome();
    }


    /**
     * 社区网点生态贡献奖
     * 1: 7天内(不包含当天的前7天)
     * 2: 365天内(不包含当天的前365天)
     *
     * @throws Exception
     */
    @XxlJob("communityNetworkEcologicalCultivationAward")
    public void communityNetworkEcologicalCultivationAward() throws Exception {
        userEcologyHatchIncomeService.communityNetworkEcologicalCultivationAward();
    }


    /**
     * 城市服务中心培育奖发放
     * @throws Exception
     */
    @XxlJob("ecologicalCultivationOfUrbanServiceCenter")
    public void ecologicalCultivationOfUrbanServiceCenter() throws Exception {
        userEcologyHatchIncomeService.ecologicalCultivationOfUrbanServiceCenter();
    }


    /**
     * 城市服务中心生态贡献奖
     * @throws Exception
     */
    @XxlJob("urbanServiceCenterEcologicalContribution")
    public void urbanServiceCenterEcologicalContribution() throws Exception {
        userEcologyHatchIncomeService.urbanServiceCenterEcologicalContribution();
    }


    /**
     * DAO-生态培育奖
     * 1: 上周(周一到周日)
     * 2: 365天内(不包含当天的前365天)
     * @throws Exception
     */
    @XxlJob("daoEcologyCultivateIncome")
    public void daoEcologyCultivateIncome() throws Exception {
        List<EcologyHatchDaoIncomeConf> list = ecologyHatchDaoIncomeConfDao.getListByStatusAndType(EcologyIncomeTypeEnum.DAO_CULTIVATION_AWARD, Boolean.TRUE);
        list.forEach(userEcologyHatchIncomeService::daoEcologyCultivateIncome);
    }


    /**
     * dao贡献奖
     * 统计维度 :
     * 1: 7天内(不包含当天的前7天)
     * 2: 365天内(不包含当天的前365天)
     * @throws Exception
     */
    @XxlJob("daoEcologyContributionIncome")
    public void daoEcologyContributionIncome() throws Exception {
        List<EcologyHatchDaoIncomeConf> list = ecologyHatchDaoIncomeConfDao.getListByStatusAndType(EcologyIncomeTypeEnum.DAO_CONTRIBUTION_AWARD, Boolean.TRUE);
        list.forEach(userEcologyHatchIncomeService::daoEcologyContributionIncome);
    }

    /**
     * DAO-持仓奖
     * @throws Exception
     */
    @XxlJob("daoPositionBonusAward")
    public void daoPositionBonusAward() throws Exception {
        List<EcologyHatchDaoIncomeConf> list = ecologyHatchDaoIncomeConfDao.getListByStatusAndType(EcologyIncomeTypeEnum.DAO_POSITION_BONUS_AWARD, Boolean.TRUE);
        list.forEach(userEcologyHatchIncomeService::daoPositionBonusAward);
    }

    /**
     * 分红池流入到钱包(每周二)
     * @throws Exception
     */
    @XxlJob("ecologyBonusPoolFlowInto")
    public void ecologyBonusPoolFlowInto() throws Exception {
        List<Long> ids = ecologyHatchConfDao.getDaoIdByConfCollectionId();
        ids.forEach(userEcologyHatchIncomeService::ecologyBonusPoolFlowInto);

    }
    /**
     * 释放双方分账(每周三)
     * @throws Exception
     */
    @XxlJob("ecologyReleaseSeparateAccount")
    public void ecologyReleaseSeparateAccount() throws Exception {
        List<EcologyHatchShareProfit> list = ecologyHatchShareProfitDao.getListByType(EcologyHatchShareProfitTypeEnum.BOTH_PARTIES_ACCOUNT);
        list.forEach(userEcologyHatchIncomeService::ecologyDaoRelease);
    }

    /**
     * 释放市值管理(每个月15号)
     * @throws Exception
     */
    @XxlJob("ecologyReleaseMarketValueManagement")
    public void ecologyReleaseMarketValueManagement() throws Exception {
        DateTime beginMonth = DateUtil.beginOfMonth(DateUtil.lastMonth());
        // 上个月的池子
        List<MarketManagementDaoPool> lastPools = marketManagementDaoPoolDao.getLastPools(beginMonth);
        lastPools.forEach(userEcologyHatchIncomeService::ecologyReleaseMarketValueManagement);
    }

    /**
     * 每日统计分成比例
     * @throws Exception
     */
    @XxlJob("ecologyStatisticalProportion")
    public void ecologyStatisticalProportion() throws Exception {
        List<EcologyHatchCollecionShareProfitConf> list = ecologyHatchCollecionShareProfitConfDao.getListGroupCollectionIdByType(EcologyHatchShareProfitTypeEnum.BOTH_PARTIES_ACCOUNT);
        list.forEach(userEcologyHatchIncomeService::ecologyStatisticalProportion);
    }

    /**
     * 结算分成(MQ不结算/结算失败 冗余结算)
     * @throws Exception
     */
    @XxlJob("candidateSettleDivideInto")
    public void candidateSettleDivideInto() throws Exception {
        List<UserEcologyHatchRecords> list = userEcologyHatchRecordsDao.getListByisSettleDivideIntoAndTime(Boolean.FALSE);
        for (UserEcologyHatchRecords userEcologyHatchRecords : list) {
            String key = RedisKeyEnum.ECOLOGY_HATCH_DIVIDE_INTO_TOPIC_LOCK.getKey() + userEcologyHatchRecords.getId();
            RLock lock = redisson.getLock(key);
            try {
                boolean res = lock.tryLock(3, TimeUnit.SECONDS);
                if (!res){
                    throw new GlobalException("积分分成正在处理");
                }
                UserEcologyHatchRecords userEcologyHatchRecordsDaoById = userEcologyHatchRecordsDao.getById(userEcologyHatchRecords.getId());
                log.info("熔炼-分成处理 记录id:{},查询结果:{}", userEcologyHatchRecords.getId(),userEcologyHatchRecordsDaoById);
                ecologySmeltingService.newDivideInto(userEcologyHatchRecordsDaoById);
            } catch (Exception e) {
                WeChatUtil.sendLiGenWeChatMessage(StrUtil.format("熔炼-分成处理失败 记录id：{},异常:{}", userEcologyHatchRecords.getId(), e.getMessage()));
                log.error("熔炼-分成处理失败 记录id：{},异常:{}", userEcologyHatchRecords.getId(), e.getMessage());
            }finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }

    /**
     * 回流产品库存(铸造商品)
     * @throws Exception
     */
    @XxlJob("refluxProductStock")
    public void refluxProductStock() throws Exception {
        List<EcologyReforgeConf> list = ecologyReforgeConfService.getListByStatus(Boolean.TRUE);
        list.forEach(ecologyReforgeConfService::addProductStock);
    }

    /**
     * 共振分润系数同步
     */
    @XxlJob("resonanceCoefficientsAreSynchronized")
    public void resonanceSeparationCoefficientsAreSynchronized() throws Exception {
        // 共振分润系数同步
        adminEcologyIncomeConfService.resonanceSeparationCoefficientsAreSynchronized();
    }

    /**
     * 市值管理解冻
     * @throws Exception
     */
    @XxlJob("managementThaw")
    public void managementThaw() throws Exception {
        userEcologyHatchIncomeService.managementThaw();
    }



    /**
     * 给符合赠送条件的用户增加 可消耗熔炼份数
     * @throws Exception
     */
    @XxlJob("addUserEcologyGiftCount")
    public void addUserEcologyGiftCount() throws Exception {
        ecologyHatchExchangeConfService.addUserEcologyGiftCount();
    }

    /**
     * 每周共识度调整
     * @throws Exception
     */
    @XxlJob("consensusAdjustmentTask")
    public void consensusAdjustmentTask() throws Exception {
        userConsensusService.consensusAdjustmentTask();
    }

}
